package com.cse587.util;

import java.util.HashSet;
import java.util.Set;

import com.cse587.gae.entities.Country;
import com.cse587.gae.dto.CountryDto;

public class Util {
	public static String URLROOT = "http://www.fao.org/countryprofiles/geoinfo/ws/";
	public static String geoCountryURL = "http://api.geonames.org/countryInfo?username=gassa";
	public static String gooeleGeoURL = "http://maps.googleapis.com/maps/api/geocode/xml?";

	public static final String NS = "localhost:8080/myapp/";
	public static final String ingoreWords = "the , of, and";

	public static final String COUNTRY_NAME_NO_FOUND = "unable to find the country name";
	public static final String FAIL_TO_LOCATE_BY_LAT_LONG = "fail to locate country by given latitude and longtitude";
	public static final String INVALID_INPUT_PARAM = "invalid input parameter";

	public static int safeLongToInt(long l) {
		if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) {
			throw new IllegalArgumentException(l
					+ " cannot be cast to int without changing its value.");
		}
		return (int) l;
	}

	public static Set<String> tokenCountryName(String alternativeNames,
			com.cse587.entities.Country country) {
		Set<String> tokens = new HashSet<String>();

		String processString = alternativeNames.replaceAll("[^a-zA-Z0-9,\\s]",
				"");
		processString = processString + " "
				+ country.getFullName().replaceAll("[^a-zA-Z0-9,\\s]", "");
		String[] rawTokens = processString.split(",| ");
		for (String string : rawTokens) {
			if (string.trim().length() > 1 && !string.trim().equals("the")
					&& !string.trim().equals("of")
					&& !string.trim().equals("and")) {
				tokens.add(string.trim());
			}
		}

		tokens.add(country.getCodeISO3().toLowerCase());
		return tokens;
	}

	public static boolean isNumber(String num) {
		try {
			Double.parseDouble(num);
		} catch (NumberFormatException nfe) {
			return false;
		}
		return true;
	}

	/*
	 * Haversine formula distance
	 */
	public static double distFrom(double lat1, double lng1, double lat2,
			double lng2) {
		double earthRadius = 3958.75;
		double dLat = Math.toRadians(lat2 - lat1);
		double dLng = Math.toRadians(lng2 - lng1);
		double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
				+ Math.cos(Math.toRadians(lat1))
				* Math.cos(Math.toRadians(lat2)) * Math.sin(dLng / 2)
				* Math.sin(dLng / 2);
		double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
		double dist = earthRadius * c;

		return dist;
	}
	
	public static CountryDto convertCountryToDTO(Country c){
		CountryDto dto = new CountryDto();
		
		dto.setCapital(c.getCapital());
		dto.setCapitalLat(c.getCapitalLat());
		dto.setCapitalLong(c.getCapitalLong());
		dto.setCountryName(c.getFullName());
		dto.setIso3Code(c.getCodeISO3());
		dto.setMaxLat(c.getMinLat());
		dto.setMaxLong(c.getMaxLong());
		dto.setMinLat(c.getMinLat());
		dto.setMinLong(c.getMinLong());
		dto.setUncode(String.valueOf(c.getUncode()));
		
		return dto;
	}
}
